<script setup>
import {Department} from '@/utils/resource'
import {confirm} from '@/utils/element-helper'
import {nextTick, onMounted, ref} from "vue";
import {useRouter} from "vue-router";

import {departmentStore} from "@/store/department";

const loading = ref(false)
const departmentS = departmentStore()
const router = useRouter()

async function loadTree() {
  loading.value = true
  await departmentS.loadDepartments()
  await nextTick()
  loading.value = false
}

loadTree()

function handleAdd() {
  router.push({path: "/department/new"})
}

function handleEdit(index, row, id) {
  router.push({path: "/department/" + row.id})
}

function handleChild(index, row, parent) {
  router.push({path: "/department/new/" + row.id});
}

function handleDelete(index, row, id) {
  confirm({_content: "删除部门将一并删除所有子部门, 是否继续?"}, () => Department.del(row.id), (resp) => loadTree())
}

</script>
<template>
  <el-form :inline="true">
    <el-form-item style="float: right">
      <el-button type="success" @click="handleAdd" icon="CirclePlus" plain>新增</el-button>
    </el-form-item>
  </el-form>
  <el-table
      :data="departmentS.departments"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      v-loading="loading"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
    <el-table-column
        prop="name"
        label="名称">
    </el-table-column>
    <el-table-column
        prop="leader"
        label="负责人">
    </el-table-column>
    <el-table-column
        prop="updated"
        label="更新时间">
    </el-table-column>
    <el-table-column label="操作" width="300" align="center">
      <template #default="scope">
        <el-button
            type="warning"
            size="small"
            @click="handleEdit(scope.$index, scope.row, scope.row.id)">编辑
        </el-button>
        <el-button type="success" size="small" icon="CirclePlus" @click="handleChild(scope.$index, scope.row,scope.row.parent)" plain>添加子部门</el-button>
        <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.$index, scope.row, scope.row.id)">删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>


</style>
